package com.gz.furnitures.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//这里不写成abstract类也能运行
//写成abstract类是因为:
//(1)说明该类不能实例化，说明不是为了直接使用而设计的
//(2)如果有更复杂的设计要求有必须要实现的方法，该方法可以设置为abstract方法
public abstract class BasicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //这里的action即其方法
        String action = request.getParameter("action");

        //利用反射+动态绑定
        try {
            //根据动态绑定机制，这里的this指子级的login或register
            Method declaredMethod = this.getClass().getDeclaredMethod(
                    action, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.invoke(this,request,response);
        } catch (Exception e) {
            //这里再将捕获到的异常抛给TransactionFilter
            //如果用 e.printStackTrace();，那么不会抛给TransactionFilter，在这里就结束了
            //即BasicServlet的子类捕获到的异常->BasicServlet->TransactionFilter
            throw new RuntimeException(e);
//            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
